package com.dx.VegetableOxygenBarBackEnd.service.impl;

import com.dx.VegetableOxygenBarBackEnd.common.ErrorCode;
import com.dx.VegetableOxygenBarBackEnd.config.CosPropertiesConfig;
import com.dx.VegetableOxygenBarBackEnd.exception.BusinessException;
import com.dx.VegetableOxygenBarBackEnd.service.CosService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 腾讯云对象存储    服务
 */
@Service
public class CosServiceImpl implements CosService {
    @Resource
    private CosPropertiesConfig cosPropertiesConfig;

    @Override
    public COSClient initCOSClient() {
        String secretId = cosPropertiesConfig.getSecretId();
        String secretKey = cosPropertiesConfig.getSecretKey();
        String region = cosPropertiesConfig.getRegion();
        // 初始化用户身份信息（secretId, secretKey）
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 设置存储桶所在的区域
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 创建 COS 客户端
        return new COSClient(cred, clientConfig);
    }


    @Override
    public String uploadFile(MultipartFile file, String avatarsUrl) throws IOException {
        String bucketName = cosPropertiesConfig.getBucketName();
        String region = cosPropertiesConfig.getRegion();
        COSClient cosClient = initCOSClient();
        try {
            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            File localFile = File.createTempFile("temp", null);
            file.transferTo(localFile);

            // 将文件上传至指定存储桶
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, avatarsUrl + fileName, localFile);
            cosClient.putObject(putObjectRequest);

            // 构建文件的外部访问URL
            String fileUrl = "https://" + bucketName + ".cos." + region + ".myqcloud.com/"+avatarsUrl + fileName;

            // 返回上传后的文件 URL
            return fileUrl;
        } finally {
            cosClient.shutdown();
        }
    }

    @Override
    public boolean deleteFile(String fileUrl, String avatarsUrl) {
        try {
            // 解析文件的存储桶名称和文件路径
            String bucketName = cosPropertiesConfig.getBucketName();
            // 解析 fileUrl 来获取文件的 key（路径）
            String fileKey = fileUrl.substring(fileUrl.indexOf(avatarsUrl));  // 假设文件路径以 'avatars/' 开头
            // 创建 COS 客户端
            COSClient cosClient = initCOSClient();
            // 删除文件
            cosClient.deleteObject(bucketName, fileKey);
            return true;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
    }

}
